package com.example.daily.ui.foodrecord

import android.util.Log
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.example.daily.data.dao.FoodRecordDao
import com.example.daily.data.entity.FoodRecord
import com.example.daily.data.UserPreferences
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.launch
import java.time.LocalDateTime
import java.time.ZoneId
import java.time.ZoneOffset
import java.util.Date
import javax.inject.Inject

data class FoodRecordUiState(
    val foodRecords: List<FoodRecord> = emptyList(),
    val isLoading: Boolean = false,
    val error: String? = null,
    val totalCalories: Int = 0
)

@HiltViewModel
class FoodRecordViewModel @Inject constructor(
    private val foodRecordDao: FoodRecordDao,
    private val userPreferences: UserPreferences
) : ViewModel() {
    private val _uiState = MutableStateFlow(FoodRecordUiState())
    val uiState: StateFlow<FoodRecordUiState> = _uiState

    init {
        loadFoodRecords()
    }

    private fun loadFoodRecords() {
        viewModelScope.launch {
            try {
                _uiState.value = _uiState.value.copy(isLoading = true)
                val userId = userPreferences.getUserId().first()
                    ?: throw IllegalStateException("用户未登录")
                
                val now = LocalDateTime.now()
                val zoneId = ZoneId.systemDefault()
                val startOfDay = now.toLocalDate().atStartOfDay(zoneId).toInstant().toEpochMilli()
                val endOfDay = now.toLocalDate().plusDays(1).atStartOfDay(zoneId).toInstant().toEpochMilli()
                
                Log.d("FoodRecordViewModel", "加载今日食物记录")
                Log.d("FoodRecordViewModel", "当前时间: ${Date()}")
                Log.d("FoodRecordViewModel", "开始时间: ${Date(startOfDay)}")
                Log.d("FoodRecordViewModel", "结束时间: ${Date(endOfDay)}")
                
                foodRecordDao.getFoodRecordsForUserInTimeRange(userId, startOfDay, endOfDay)
                    .collect { records ->
                        Log.d("FoodRecordViewModel", "获取到食物记录: ${records.size}条")
                        records.forEach { record ->
                            Log.d("FoodRecordViewModel", "食物记录: ${record.foodName}, 时间: ${Date(record.recordDate)}")
                        }
                        _uiState.value = _uiState.value.copy(
                            foodRecords = records,
                            totalCalories = records.sumOf { it.calories },
                            isLoading = false
                        )
                    }
            } catch (e: Exception) {
                Log.e("FoodRecordViewModel", "加载食物记录失败", e)
                _uiState.value = _uiState.value.copy(
                    error = "加载食物记录失败: ${e.message}",
                    isLoading = false
                )
            }
        }
    }

    fun addFoodRecord(foodName: String, calories: Int, recordDate: LocalDateTime) {
        viewModelScope.launch {
            try {
                val userId = userPreferences.getUserId().first()
                    ?: throw IllegalStateException("用户未登录")
                    
                val timestamp = recordDate.atZone(ZoneId.systemDefault()).toInstant().toEpochMilli()
                Log.d("FoodRecordViewModel", "添加食物记录 - 时间戳: $timestamp (${Date(timestamp)})")
                    
                val foodRecord = FoodRecord(
                    userId = userId,
                    foodName = foodName,
                    calories = calories,
                    recordDate = timestamp
                )
                foodRecordDao.insertFoodRecord(foodRecord)
                loadFoodRecords()
            } catch (e: Exception) {
                _uiState.value = _uiState.value.copy(
                    error = "添加食物记录失败: ${e.message}"
                )
            }
        }
    }

    fun deleteFoodRecord(foodRecord: FoodRecord) {
        viewModelScope.launch {
            try {
                foodRecordDao.deleteFoodRecord(foodRecord)
                loadFoodRecords()
            } catch (e: Exception) {
                _uiState.value = _uiState.value.copy(
                    error = "删除食物记录失败: ${e.message}"
                )
            }
        }
    }
} 